package com.hui.controller.user;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.hui.entity.dao.ShopUser;
import com.hui.entity.dao.StoreOrder;
import com.hui.entity.dto.OrderExtendDto;
import com.hui.entity.enums.*;
import com.hui.entity.vo.ComputeVo;
import com.hui.entity.vo.StoreOrderQueryVo;
import com.hui.handler.exception.SystemException;
import com.hui.model.order.*;
import com.hui.service.StoreOrderService;
import com.hui.service.UserService;
import com.hui.service.modules.OrderSupplyService;
import com.hui.util.BeanCopyUtils;
import com.hui.util.ResponseResult;
import com.hui.util.module.GetUserInfo;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.LinkedHashMap;
import java.util.Map;


@RestController
@CrossOrigin
@RequiredArgsConstructor
@Slf4j
@RequestMapping("/api/order")
public class StoreOrderController {

    private final UserService userService; //用户表
    private final StoreOrderService storeOrderService;
    private final OrderSupplyService orderSupplyService;//订单的一些方法

    /**
     * 订单确认
     *
     * @param param
     * @param request
     * @return
     */
    @PostMapping("/confirm")
    @ApiOperation(value = "订单确认", notes = "订单确认")
    public ResponseResult confirm(@RequestBody ConfirmOrderParam param, HttpServletRequest request) {
        Long uid = GetUserInfo.getUid(request);
        ShopUser shopUser = userService.getById(uid);
        return storeOrderService.confirmOrder(shopUser, param.getCartId());
    }

    /**
     * 计算订单金额
     *
     * @param param
     * @param request
     * @return
     */

    @PostMapping("/computed/{key}")
    public ResponseResult computedOrder(@RequestBody ComputeOrderParam param, HttpServletRequest request) {
        Long uid = GetUserInfo.getUid(request);
        ShopUser shopUser = userService.getById(uid);
        String key = param.getKey();

        //去获取订单的详细信息
        Map<String, Object> map = orderSupplyService.check(uid, param);
        if (OrderLogEnum.EXTEND_ORDER.getValue().equals(map.get("status"))
                || OrderLogEnum.PINK_ORDER_FAIL_1.getValue().equals(map.get("status"))
                || OrderLogEnum.PINK_ORDER_FAIL_2.getValue().equals(map.get("status"))) {
            return ResponseResult.okResult(map.get("msg").toString());
        }

        //计算用户订单总价
        ComputeVo computeVo = storeOrderService.computedOrder(shopUser, key,
                param.getCouponId(),//(value = "优惠券ID")
                param.getUseIntegral(), //(value = "使用积分 1-表示使用")
                param.getShippingType(), //(value = "配送方式 1=快递 ，2=门店自提")
                param.getAddressId()//(value = "地址ID")
        );

        map.put("result", computeVo);
        map.put("status", OrderLogEnum.NONE_ORDER.getValue());
        return ResponseResult.okResult(map);
    }

    /**
     * 订单创建
     */
    //(value = "订单创建", type = 1)
    @PostMapping("/create/{key}")
    //(value = "订单创建",notes = "订单创建")
    public ResponseResult create(@RequestBody OrderParam param, HttpServletRequest request) {
        Long uid = GetUserInfo.getUid(request);
        ShopUser shopUser = userService.getById(uid);//用户信息
        String key = param.getKey();//唯一的订单ID

        ComputeOrderParam computeOrderParam = new ComputeOrderParam();
        computeOrderParam = BeanCopyUtils.copyBean(param, ComputeOrderParam.class);
        Map<String, Object> map = orderSupplyService.check(shopUser.getUid(), computeOrderParam);
        if (OrderLogEnum.EXTEND_ORDER.getValue().equals(map.get("status"))
                || OrderLogEnum.PINK_ORDER_FAIL_2.getValue().equals(map.get("status"))
                || OrderLogEnum.PINK_ORDER_FAIL_1.getValue().equals(map.get("status"))) {
            return ResponseResult.okResult(map);
        }

        //创建订单
        StoreOrder order = storeOrderService.createOrder(shopUser, key, param);

        if (ObjectUtil.isNull(order)) {
            throw new SystemException(AppHttpCodeEnum.NO_PARAMETE_OPERATE.getCode(), "订单生成失败");
        }

        String orderId = order.getOrderId();

        OrderExtendDto orderDTO = new OrderExtendDto();
        orderDTO.setKey(key);
        orderDTO.setOrderId(orderId);
        map.put("status", OrderLogEnum.CREATE_ORDER_SUCCESS.getValue());
        map.put("result", orderDTO);

        //开始处理支付
        //处理金额为0的情况
        if (order.getPayPrice().compareTo(BigDecimal.ZERO) <= 0 && !param.getPayType().equals(PayTypeEnum.INTEGRAL.getValue())) {
            storeOrderService.yuePay(orderId, shopUser.getUid());
            map.put("payMsg", "支付成功");
            return ResponseResult.okResult(map);
        }

        orderSupplyService.goPay(map, orderId, shopUser.getUid(),
                param.getPayType(), param.getFrom(), orderDTO);
        return ResponseResult.okResult(map);
    }

    /**
     * 订单列表
     */
    //(value = "查看订单列表", type = 1)
    @GetMapping("/list")
    //(value = "订单列表",notes = "订单列表")
    public ResponseResult orderList(OrderListParam orderListParam
            , HttpServletRequest request) {
        int type = 0;
        if (ObjectUtil.isNotNull(orderListParam.getType())) {
            type = orderListParam.getType();
        }
        int page = 1;
        int limit = 50;
        Long uid = GetUserInfo.getUid(request);
        return ResponseResult.okResult(storeOrderService.orderListByPage(uid, type, page, limit));
    }


    /**
     * 订单删除
     */
    @PostMapping("/del")
    @ApiOperation(value = "订单删除", notes = "订单删除")
    public ResponseResult<Boolean> orderDel(@Validated @RequestBody DoOrderParam param, HttpServletRequest request) {
        Long uid = GetUserInfo.getUid(request);
        storeOrderService.removeOrder(param.getUni(), uid);
        return ResponseResult.okResult();
    }


    /**
     * 订单详情
     */
    //(value = "查看订单详情", type = 1)
    @GetMapping("/detail/{key}")
    //(name = "key", value = "唯一的key", paramType = "query", dataType = "string")
    @ApiOperation(value = "订单详情", notes = "订单详情")
    public ResponseResult detail(@PathVariable String key, HttpServletRequest request) {
        Long uid = GetUserInfo.getUid(request);
        if (StrUtil.isEmpty(key)) {
            throw new SystemException(AppHttpCodeEnum.NO_PARAMETE_OPERATE.getCode(), "参数错误");
        }
        StoreOrderQueryVo storeOrder = storeOrderService.getOrderInfo(key, uid);
        if (ObjectUtil.isNull(storeOrder)) {
            throw new SystemException(AppHttpCodeEnum.NO_PARAMETE_OPERATE.getCode(), "订单不存在");
        }
        /*
        门店信息
        storeOrder = creatShareProductService.handleQrcode(storeOrder,path);
        */
        return ResponseResult.okResult(storeOrderService.handleOrder(storeOrder));
    }

    /**
     * 订单取消   未支付的订单回退积分,回退优惠券,回退库存
     */

    @PostMapping("/cancel")
    @ApiOperation(value = "订单取消", notes = "订单取消")
    public ResponseResult cancelOrder(@Validated @RequestBody HandleOrderParam param, HttpServletRequest request) {
        Long uid = GetUserInfo.getUid(request);
        storeOrderService.cancelOrder(param.getId(), uid);
        return ResponseResult.okResult();
    }

    /**
     * 订单支付
     */
    @PostMapping("/pay")
    @ApiOperation(value = "订单支付", notes = "订单支付")
    public ResponseResult<Map<String, Object>> pay(@Valid @RequestBody PayParam param, HttpServletRequest request) {
        Map<String, Object> map = new LinkedHashMap<>();
        Long uid = GetUserInfo.getUid(request);
        StoreOrderQueryVo storeOrder = storeOrderService
                .getOrderInfo(param.getUni(), uid);
        if (ObjectUtil.isNull(storeOrder)) {
            throw new SystemException(AppHttpCodeEnum.NO_PARAMETE_OPERATE.getCode(), "订单不存在");
        }

        if (OrderInfoEnum.REFUND_STATUS_1.getValue().equals(storeOrder.getPaid())) {
            throw new SystemException(AppHttpCodeEnum.NO_PARAMETE_OPERATE.getCode(), "该订单已支付");
        }

        String orderId = storeOrder.getOrderId();

        OrderExtendDto orderDTO = new OrderExtendDto();
        orderDTO.setOrderId(orderId);
        map.put("status", "SUCCESS");
        map.put("result", orderDTO);


        if (storeOrder.getPayPrice().compareTo(BigDecimal.ZERO) <= 0 && !param.getPaytype().equals(PayTypeEnum.INTEGRAL.getValue())) {
            storeOrderService.yuePay(orderId, uid);
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS.getCode(), "支付成功", map);
        }

        //处理是否已经修改过订单价格，如果修改用新的单号去拉起支付
        if (StrUtil.isNotBlank(storeOrder.getExtendOrderId())) {
            orderId = storeOrder.getExtendOrderId();
        }


        orderSupplyService.goPay(map, orderId, uid, param.getPaytype(), param.getFrom(), orderDTO);

        return ResponseResult.okResult(map);
    }
}
